package com.tripspins.app.helper;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;


import com.tripspins.app.exception.NoConnectionException;
import com.tripspins.app.exception.OfflineModeException;
import com.tripspins.app.interfaces.OnTaskCompleted;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by joaortk on 05/09/13.
 */
public class HttpHelper {

    OnTaskCompleted activity;
    HttpGet httpGet;

    public void getBitmap(String url, OnTaskCompleted activity, Activity same)
            throws OfflineModeException, NoConnectionException {

        boolean online = PreferencesHelper.getSharedPreference(same, "pref_key_internet_connection",false);
        if(!online) throw new OfflineModeException();
        online = DeviceCheckHelper.isNetworkConnected(same);
        if(!online) throw new NoConnectionException();

        httpGet = new HttpGet();
        httpGet.execute(new String[]{url});
        this.activity = activity;
    }

    class HttpGet extends AsyncTask<String,Void,Bitmap> {
        @Override
        protected Bitmap doInBackground(String... params) {
            Bitmap bmp = null;
            URL url = null;
            try {
                url = new URL(params[0]);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setDoInput(true);
                connection.connect();
                InputStream input = connection.getInputStream();
                bmp = BitmapFactory.decodeStream(input);


            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return bmp;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            activity.onTaskCompleted(bitmap);
        }
    }
}
